package com.tomtop.services.cart;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.tomtop.services.impl.product.EntityMapService;
import com.tomtop.services.impl.product.ProductEnquiryService;
import com.tomtop.services.impl.product.price.PriceService;
import com.tomtop.services.product.IProductService;
import com.tomtop.utils.DoubleCalculateUtils;
import com.tomtop.utils.FoundationService;
import com.tomtop.valueobjects.BundleCartItem;
import com.tomtop.valueobjects.CartItem;
import com.tomtop.valueobjects.SingleCartItem;
import com.tomtop.valueobjects.product.ProductLite;
import com.tomtop.valueobjects.product.price.BundlePrice;
import com.tomtop.valueobjects.product.price.Price;
import com.tomtop.valueobjects.product.spec.IProductSpec;
import com.tomtop.valueobjects.product.spec.ProductSpecBuilder;

@Service
public class CartService {

	Logger logger = Logger.getLogger(CartService.class);

	@Autowired
	FoundationService foundationService;
	@Autowired
	ProductEnquiryService productEnquiryService;
	@Autowired
	EntityMapService entityMapService;
	@Autowired
	PriceService priceService;
	@Autowired
	IProductService IProductService;

	public List<CartItem> getCartItems(List<CartItem> items, int siteID,
			int languageID, String ccy) {
		List<String> listingids = Lists.newLinkedList();
		for (CartItem it : items) {
			if (it instanceof BundleCartItem) {
				listingids.addAll(((BundleCartItem) it).getAllListingId());
			} else {
				listingids.add(it.getClistingid());
			}
		}
		List<String> distinctIds = listingids;
		if (distinctIds == null || distinctIds.size() == 0) {
			return Lists.newArrayList();
		}
		logger.debug("distinctIds==={}" + distinctIds);
		// 取得产品信息
		List<ProductLite> products = productEnquiryService
				.getProductLiteByListingIDs(distinctIds, siteID, languageID);
		products = ImmutableSet.copyOf(products).asList();
		Map<String, ProductLite> productMap = Maps.uniqueIndex(products,
				p -> p.getListingId());

		for (CartItem ci : items) {
			if (ci instanceof SingleCartItem) {
				IProductSpec spec = ProductSpecBuilder
						.build(ci.getClistingid()).setQty(ci.getIqty()).get();
				ci.setPrice(priceService.getPrice(spec, ccy, ci.getStorageID()));
				ProductLite p = productMap.get(ci.getClistingid());
				if (p != null) {
					ci.setCtitle(p.getTitle());
					ci.setCurl(p.getUrl());
					ci.setCimageurl(p.getImageUrl());
					ci.setSku(p.getSku());
					ci.setIstatus(p.getIstatus());
					Map<String, String> attributeMap = entityMapService
							.getAttributeMap(ci.getClistingid(), languageID);
					ci.setAttributeMap(attributeMap);
				}
			} else if (ci instanceof BundleCartItem) {
				List<String> childIDs = new ArrayList<String>();
				childIDs.add(((BundleCartItem) ci).getClistingid());
				for (SingleCartItem sc : ((BundleCartItem) ci).getChildList()) {
					childIDs.add(sc.getClistingid());
				}
				IProductSpec spec = ProductSpecBuilder
						.build(ci.getClistingid()).bundleWith(childIDs)
						.setQty(ci.getIqty()).get();
				Price bprice = priceService.getPrice(spec, ccy, ci.getStorageID());
				// 设置捆绑价格
				((BundleCartItem) ci).setAllPrice(bprice);
				BundlePrice p = (BundlePrice) bprice;
				Map<String, Price> mapprice1 = new HashMap<String, Price>();
				logger.info("p.getBreakdown()==" + p.getBreakdown().size());
				if (p != null) {
					mapprice1 = Maps.uniqueIndex(p.getBreakdown(),
							objprice -> objprice.getListingId());
				}
				// -----主产品
				ProductLite mainproduct = productMap.get(ci.getClistingid());
				if (mainproduct != null) {
					ci.setCtitle(mainproduct.getTitle());
					ci.setCurl(mainproduct.getUrl());
					ci.setCimageurl(mainproduct.getImageUrl());
					ci.setSku(mainproduct.getSku());
					ci.setIstatus(mainproduct.getIstatus());
					Map<String, String> attributeMap2 = entityMapService
							.getAttributeMap(ci.getClistingid(), languageID);
					ci.setAttributeMap(attributeMap2);
				}
				if (null != mapprice1) {
					ci.setPrice(mapprice1.get(ci.getClistingid()));
				}
				// -----子产品
				for (SingleCartItem sci : ((BundleCartItem) ci).getChildList()) {
					ProductLite cp = productMap.get(sci.getClistingid());
					if (cp != null) {
						sci.setCtitle(cp.getTitle());
						sci.setCurl(cp.getUrl());
						sci.setCimageurl(cp.getImageUrl());
						sci.setSku(cp.getSku());
						sci.setIstatus(cp.getIstatus());
						Map<String, String> attributeMap2 = entityMapService
								.getAttributeMap(sci.getClistingid(),
										languageID);
						sci.setAttributeMap(attributeMap2);
					}
					if (null != mapprice1) {
						sci.setPrice(mapprice1.get(sci.getClistingid()));
					}
				}
			}
		}
		return items;
	}

	public double getTotal(List<CartItem> items) {
		DoubleCalculateUtils duti = new DoubleCalculateUtils(0.0);
		for (CartItem ci : items) {
			if (ci.getPrice() != null) {
				duti = duti.add(ci.getPrice().getPrice());
			}
		}
		return duti.doubleValue();
	}

	/**
	 * 判断是否够库存
	 * 
	 * @param itemID
	 * @param qty
	 * @param listingids
	 * @return
	 */
	public boolean isEnoughQty(CartItem cartItem) {
		if (cartItem instanceof SingleCartItem) {
			if (IProductService.checkInventory(cartItem.getClistingid(),
					cartItem.getIqty()) && cartItem.getIqty() <= 999) {
				return true;
			}
		} else if (cartItem instanceof BundleCartItem) {
			List<SingleCartItem> blist = ((BundleCartItem) cartItem)
					.getChildList();
			for (int i = 0; i < blist.size(); i++) {
				if (!IProductService.checkInventory(blist.get(i)
						.getClistingid(), blist.get(i).getIqty())
						&& blist.get(i).getIqty() > 999) {
					return false;
				}
			}
			return true;
		}
		return false;
	}

}
